#include "MainTask.h"
#include "WindowManager.h"
#include "UIMessage.h"
#include "GUI_Key.h"
#include "LcdControl.h"

#include "dlg.h"
#include "GUI_Timer.h"

#include "GUI_Message.h"
#include "..\interface\ccl.h"

#include "GUI_LCD.h"
#include "ipc.h"
#include "system_time.h"
#include "system_info.h"
#include "system_config.h"
#include "contact.h"
#include "call_log.h"
#include "channel_favorite.h"
#include "cookies.h"
#include "gpio.h"
#include "adc.h"

#include "rt_indicator.h"

#include "adc.h"

#include "macService.h"

#include "storeChannel.h"

#include "usart.h"
Window VirtualWindow;

static bool  HasInNormlaTransaction  = false;


static void VirtualWndCB(WM_Message* pMsg)
{
    if(pMsg->msgType == WM_TIMER ){
		switch(pMsg->data_v)
		{
			/** 群组消息通知黄灯亮超时熄灭 */
			case 126:
				LedYellowOff();
				GUI_DestroyTimer(&VirtualWindow, 126);
				break;
			
			case 127:
				{
					WM_Message msg;
				
					CCL_StopRx();
					
					RTState_StopRx();	
					msg.data_v  = 0;	

					msg.pTarget  = WM_GetFocus();
					msg.msgType  = USER_MSG_NOTIFY_RFRX;
					WM_SendMessage(&msg);
					
					GUI_DestroyTimer(&VirtualWindow, 127);						
				}
				break;
		}	
    }
}





void GUI_Delay()
{
	static uint32_t  OSTick  =  0;
	uint32_t CurrOSTick;
	GUI_Message guiMsg;
	WM_Message* msg;
  
  StoreChannel();
	GUI_SendKeyMsg();
  
	while((msg = PeekMessage()) != 0)
	{
		if(msg->msgType && msg->msgType && msg->pTarget->CallBack)
			msg->pTarget->CallBack(msg);
	}		
		
	while(GUI_PeekMessage(&guiMsg)){
		switch(guiMsg.type)
		{
			case IPC_MSG_CCL:
				CCL_HandleOgle(guiMsg.id, guiMsg.v, guiMsg.p);
			break;
							
			case IPC_MSG_RTC:
				if(guiMsg.id  == RTC_MSG_SECOND_TICK){
					WM_Message msg;
											
					msg.pTarget  = &mainWin;
					msg.msgType   = USER_MSG_SECOND_TICK;			
					WM_SendMessage(&msg);											 
				}
			break;
									
			case IPC_MSG_IO:{				
				
				if(guiMsg.id == IO_MSG_RF_RX){
					WM_Message msg;
						
					if(HasInNormlaTransaction == false)
					{
						break;
					}
												 
					if(guiMsg.v){
//Debug("RX io enable");
                        GUI_DestroyTimer(&VirtualWindow, 127);
                        
						RTState_StartRx();
						msg.data_v  = getChannelRssi(CclChannelIndicator);
						msg.data_v  = msg.data_v /(ADC_VALUE_MAX /10);
						if(msg.data_v == 0){
							msg.data_v  = 1;
						}
//Debug("Rx grade:%d", msg.data_v);     
					}
					else{
Debug("RX io disable");                        
                        /** 延迟500ms后判断是否仍然是接收结束  */
                        GUI_CreateTimer(&VirtualWindow, 127,  SCAN_TIMER_LENGTH);
                        break;
//						RTState_StopRx();	
//						msg.data_v  = 0;										
					}

					if(RTState_IsTxing()){	 
						break;
					}

					msg.pTarget  = WM_GetFocus();
					msg.msgType  = USER_MSG_NOTIFY_RFRX;
					WM_SendMessage(&msg);
		
				}
			}
			break;
			
			case IPC_MSG_ADC:{
				if(guiMsg.id == ADC_MSG_CCL_RSSI){
					WM_Message msg;

					if(RTState == RTState_IsRxing())
					{
						msg.pTarget  = &mainWin;
						msg.msgType  = USER_MSG_NOTIFY_RSSI_UPDATE;
						msg.data_v  = guiMsg.v;
						msg.data_v  = msg.data_v /(ADC_VALUE_MAX /10);
						if(msg.data_v == 0){
							msg.data_v  = 1;
						}	
						else if(msg.data_v > 10)
						{
							msg.data_v  = 10;
						}
	//                    Debug("Rx grade:%d", msg.data_v);                    
						WM_SendMessage(&msg);						
					}	
				}
			}
			break;									 
		}
	}
		
	
	CurrOSTick  = OSTimeGet();
		
	if(CurrOSTick - OSTick < OS_TICK_PER_GUI_PERIOD){
		OSTimeDly(OS_TICK_PER_GUI_PERIOD -  (CurrOSTick - OSTick) );
	}
	GUI_OnTick();
	OSTick  = CurrOSTick;

	Invalid();
	GUI_LCDUpdate();	
}

void WaitFPGASetup()
{
	GUI_Message guiMsg;
	while(1)
	{
		while(GUI_PeekMessage(&guiMsg))
		{
			if(guiMsg.type == IPC_MSG_CCL && guiMsg.id == FpgaInitDone)
			{
				return;
			}
		}
		OSTimeDly(1000);
	}
}

void UI_Task (void *p_arg)
{
  WM_Message* msg;
  WM_Message Msg;
  uint8_t KEYDOWN = 0;
  uint8_t InstallWin = 0;
  
  WD_SetCallback(&VirtualWindow, VirtualWndCB);
  
    
	SysCfg sysCfg;
  
/** 各种数据读出 */	
  SysInfo_Load();
  SysCfg_Load();
  Contact_Load();
  CallLog_Load();
  ChnFavorite_Load(); 
  Coki_Load();
	

  
  GUI_KeyInit();
  MessageInit();
  WM_Init();
  GUI_LCDInit();
  OSTimeDlyHMSM(0,0,0,200);
  GUI_LCDLightLoop();
  
  OSTimeDly(5);
  GUI_LCDClean();
  
  while(1)
  {
    GUI_SendKeyMsg();
    while((msg = PeekMessage()) != 0)
    {
		
      if(msg->msgType == WM_KEY && ((WM_KEY_INFO*)msg->data_p)->Pressed == KEY_DOWN)
      {
        KEYDOWN = 1;
      }
      else
      {
        switch(((WM_KEY_INFO*)msg->data_p)->Key)
        {
          case GUI_KEY_1_GROUP:
            InstallWin = 1;
            break;
          case GUI_KEY_8_WEATHER:
            InstallWin = 8;
            break;
          case GUI_KEY_5_DIRECTION:
            InstallWin = 5;
            break;
          case GUI_KEY_DEL:
            InstallWin = 0x0b;
            break;
        }
        KEYDOWN = 0;
      }
    }
    if(!KEYDOWN)
    {
      break;
    }
    OSTimeDly(50);
  }
	
  SysCfg_GetConfig(&sysCfg);
  if(!sysCfg.boatNumber)
  {
    WM_Message Msg;
    
    WIN_selfLogWinCreate();
    Msg.pTarget = &selfLogWin;
    Msg.msgType = USER_MSG_SLSETSHIPNUM;
    WM_SendMessage(&Msg);
  }
  else if(InstallWin == 1)
  {
    WIN_groupSetWinCreate();
    WM_BringToTop(&groupSetWin);
    WM_SetFocus(&groupSetWin);
  }
  else if(InstallWin == 5)
  {
    WIN_selfLogWinCreate();
    WM_BringToTop(&selfLogWin);
    WM_SetFocus(&selfLogWin);
  }
  else if(InstallWin == 8)
  {
    WIN_timeSetWinCreate();
    WM_BringToTop(&timeSetWin);
    WM_SetFocus(&timeSetWin);
  }
  else
  {
		WaitFPGASetup();
		GUI_CleanKey();
    /** 通知MAC层配置参数 */
    do{
       SysCfg   systemConfig;
      
       SysCfg_GetConfig(&systemConfig);

//       CCL_ConfigSystemParam(systemInfo.phoneId,  systemConfig.boatNumber, systemConfig.groupNumber, systemConfig.groupPwd);		
       CCL_ConfigSystemParam(SysInfo_GetId(),  systemConfig.boatNumber, systemConfig.groupNumber, systemConfig.groupPwd);		
    }while(0);
    InitStroeChannel();
    WIN_mainWinCreate();
    WIN_dialWinCreate();
    WIN_contactsWinCreate();
    WIN_calogWinCreate();
    Win_gdialWinCreate();
    WIN_analogWinCreate();
    WIN_callShipNumWinCreate();
    WIN_digitWinCreate();
    WIN_rememberChWinCreate();
    WIN_weatherWinCreate();
    WIN_beCalledWinCreate();
    WIN_editDialNumWinCreate();
    
    WM_Paint(&gdialWin, 0);
    WM_BringToTop(&mainWin);
    WM_BringToTop(&gdialWin);
    WM_SetFocus(&gdialWin);
	
	HasInNormlaTransaction  = true;
  }
  
  /** 清空消息队列 */
  do{	  
	GUI_Message msg;
	while(GUI_PeekMessage(&msg))
	{
		
	}
  }while(0);
  
  
  while(1){
    GUI_Delay();
  }
};
